package sb.simple.filter;

import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器-servlet|函数回调
 */
@Configuration
@WebFilter(filterName = "CustomFilter", urlPatterns = {"/sb/simple/*"})
public class CustomFilter implements Filter {
    private static final String TAG = CustomFilter.class.getSimpleName();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println(TAG + ":过滤器初始化init() in");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println(TAG + ":过滤器处理doFilter() in");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        StringBuffer requestURL = request.getRequestURL();
        System.out.println(TAG + ":requestURL:" + requestURL);
        String requestURI = request.getRequestURI();
        System.out.println(TAG + ":requestURI:" + requestURI);

        response.setHeader("headerA", "A");

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println(TAG + ":过滤器销毁destroy() in");
    }
}
